package com.tzh.config;

import com.tzh.config.bean.ConfigConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncTaskExcecutorConfig {

    private static final Logger log = LoggerFactory.getLogger(AsyncTaskExcecutorConfig.class);

    /**
     * 自定义异步线程池
     *
     * @return
     */
    @Bean(ConfigConstants.COMMON_SERVICE_EXECUTOR)
    public AsyncTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("Primary-Service-async：");
        executor.setMaxPoolSize(2000);
        executor.setCorePoolSize(8);
        //线程池存活时间，默认60s
        executor.setKeepAliveSeconds(300);
        //队列大小
        executor.setQueueCapacity(2000);
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                log.warn("当前任务线程池队列已满.");
            }
        });
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }
}
